import axios from 'axios'
import store from '../store/modules/user'
import router from '@/router'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 // request timeout
})

service.interceptors.request.use(config => {
  // console.log(config)
  config.headers.Authorization = 'Bearer ' + store.state.token
  return config
},
error => {
  // console.log(error)
  return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(response => {
  const success = response.data.success
  // console.log(success)
  if (success) {
    return response.data
  } else {
    return response.data // Promise.reject(new Error(response.data.message))
  }
},
error => {
  console.dir(error.response)
  if (error.response.status === 401) {
    router.push('/login')
    store.commit('user/logout')
    console.log(1)
  }
  return Promise.reject(error)
}
)

export default service
